﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using DoubleClick.Logging;
using System.Diagnostics;

namespace DoubleClick.Runner
{
    public class RunCommand : IProcessCommand
    {
        private readonly Process process = new Process();
        private ILogger logger;
        private bool isDisposed = false;

        public RunCommand(string command)
        {
            process.StartInfo.UseShellExecute = false;
            process.EnableRaisingEvents = true;
            process.StartInfo.FileName = command.ToString();
        }

        public void SetLogger(ILogger l)
        {
            logger = l;
        }

        public void Run()
        {
            if (!isDisposed)
            {
                process.Start();
                logger.Write(EventLogType.information,
                    String.Format("Il processo controllato {0} è stato avviato (pid {1}).", 
                    process.StartInfo.FileName,
                    GetProcessID()));
                process.Exited += new EventHandler(OnProcess_Exited);
            }
        }

        private void OnProcess_Exited(object s, EventArgs a)
        {
            if (!(s is Process))
                return;

            process.Exited -= OnProcess_Exited;
            if (!isDisposed)
                Run();
        }

        #region IProcessCommand Members

        public bool IsRunning
        {
            get { return !process.HasExited; }
        }

        public int GetProcessID()
        {
            return process.Id;
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            isDisposed = true;
            process.Kill();
        }

        #endregion
    }

    public interface IProcessCommand : IDisposable
    {
        bool IsRunning { get; }

        int GetProcessID();
    }
}
